#coding=utf-8
'''
Created on 2017-7-15

@author: sandy
'''
import logging
from pycommon import Const
import ClientBuild
import Game
import UserManager

TABLE_STATE_FREE        = 1
TABLE_STATE_GAME        = 2

class TableBase(object):
    
    def __init__(self, tid, hc):
        self.id = tid
        self.hc = hc
        self.usermap = {}  #seatnum --> uid
        self.hallId = -1
        for i in range(self.getSeatCount()):
            self.usermap[i] = -1
        
    
    #===================interface==============
    def getState(self):
        return TABLE_STATE_FREE

    def onUserEnter(self, uid, seatnum):
        pass
        
    def onUserLeave(self, uid,reason):
        pass
        
    def checkTable(self):
        pass
    
    def setHallId(self, hallId):
        self.hallId = hallId
    
    def getHallId(self):
        return self.hallId
       
    #===================useful func==============
    def getSeatCount(self):
        count = self.hc.get("matchNum")
        return count

    def getId(self):
        return self.id
    
    def getSeatId(self,uid):
        for i in range(self.getSeatCount()):
            if self.getUserId(i) == uid:
                return i
        return -1
    
    def getParam(self, k):
        return self.hc.get(k)

    def getUserId(self, seatnum):
        return self.usermap[seatnum]

    def getUser(self,seatnum):
        uid = self.getUserId(seatnum)
        return self.getUserByUid(uid)

    def getUserByUid(self,uid):
        return UserManager.instance.getUser(uid)

    def getUserCount(self):
        ret = 0
        for i in range(self.getSeatCount()):
            if self.getUserId(i) != -1:
                ret += 1
        return ret
    
    def hasFreeSeat(self):
        return self.getUserCount() < self.getSeatCount()
    
    def isEmptySeat(self):
        return 0 == self.getUserCount()
    
    
    def getFreeSeatNum(self):
        ret = []
        for i in range(self.getSeatCount()):
            if self.getUserId(i) == -1:
                ret.append(i)
        return ret 
    
    def getFreeSeatCount(self):
        ret = 0
        for i in range(self.getSeatCount()):
            if self.getUserId(i) == -1:
                ret += 1
        return ret      
    
    def broadcast(self, pkt):
        for uid in self.usermap.values():
            if uid != -1:
                user = self.getUserByUid(uid)
                user.sendPacket(pkt)
            
            
    def broadcastExcept(self, pkt, uid):
        users = self.getAllUsersExcept(uid)
        for user in users:
            user.sendPacket(pkt)
        
                        
    def getAllUserIds(self):
        userIds = []
        for u in self.usermap.values():
            if u != -1:
                userIds.append(u)
        return userIds

    def getAllUsers(self):
        users = []
        ids = self.getAllUserIds()
        for uid in ids:
            users.append(self.getUserByUid(uid))
        return users

    def getAllUserIdsExcept(self,exuid):
        userIds = []
        ids = self.getAllUserIds()
        for uid in ids:
            if uid != exuid:
                userIds.append(uid)
        return userIds

    def getAllUsersExcept(self,exuid):
        users = []
        userIds = self.getAllUserIdsExcept(exuid)
        for uid in userIds:
            users.append(self.getUserByUid(uid))
        return users
          
    def userEnter(self, uid):
        user = self.getUserByUid(uid)
        if self.hasFreeSeat() == False:
            logging.debug("uid=%d request enterTable and table is Full")
            return Const.ERR_TABLE_IS_FULL
        if user.getTableId() != -1 or user.getSeatNum() != -1:
            logging.debug("uid=%d request enterTable and has tableInfo")
            return Const.ERR_USER_HAS_TABLE
        seatnum = self.getFreeSeatNum()[0]
        self.usermap[seatnum] = uid
        user.setHallId(self.hallId)
        user.setTableId(self.id)
        user.setSeatNum(seatnum)
        users = self.getAllUsersExcept(uid)
        user.sendPacket(ClientBuild.tableUserInfo(seatnum, users))
        pkt = ClientBuild.tableUserEnter(uid,seatnum,user.getPhoto(),user.getNickname(),user.getSex(),user.getProp(),user.getProperty())
        self.broadcastExcept(pkt,uid)
        self.onUserEnter(uid, seatnum)
        return Const.ERR_OK
    
    def userLeave(self, uid, reason):
        user = self.getUserByUid(uid)
        seatnum = user.getSeatNum()
        curUid = self.usermap.get(seatnum)
        assert curUid == uid , "userLeave has error"
        self.broadcast(ClientBuild.tableUserLeave(user.getUid(), user.getSeatNum(),reason))
        logging.debug(u'uid = %d 发送 userLeave 8006', user.getUid())
        self.usermap[seatnum] = -1
        user.setTableId(-1)
        user.setSeatNum(-1)
        user.setHallId(-1)
        user.onLeave()
        self.onUserLeave(uid,reason)


if __name__ == '__main__':
    pass